/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cl.alanis.gui;

import cl.alanis.business.ProductoBusiness;
import cl.alanis.business.StockBusiness;
import cl.alanis.dto.*;
import cl.alanis.util.AlanisLog;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author Pía
 */
public class IngresoPPExistenteGui extends javax.swing.JDialog {
    Logger logger=AlanisLog.obtenerLogger(IngresoPPExistenteGui.class);
    DefaultListModel model;
    Integer codigoDoc=null;
    DocumentoDto documento=null;
    /**
     * Creates new form IngresoPPExistenteGui
     */
    public IngresoPPExistenteGui() {
        this.setModal(true);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel9 = new javax.swing.JLabel();
        jDialog2 = new javax.swing.JDialog();
        cmbFiltroBusqueda = new javax.swing.JComboBox();
        txtBusqueda = new javax.swing.JTextField();
        bttBusqueda = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblListaBusqueda = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel25 = new javax.swing.JLabel();
        bttLimpiarB = new javax.swing.JButton();
        bttIngresarDocumento = new javax.swing.JButton();
        txtDocumento = new javax.swing.JTextField();
        cmbDocumento = new javax.swing.JComboBox();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        lblCodigoProductoB = new javax.swing.JLabel();
        lblDescripcionB = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lblModeloAutoB = new javax.swing.JLabel();
        lblFabricanteB = new javax.swing.JLabel();
        lblTipoRepuestoB = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lblCantidadB = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblAplicacionB = new javax.swing.JLabel();
        lblAñoAutoB = new javax.swing.JLabel();
        lblMarcaAutoB = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblError = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        txtValorNeto = new javax.swing.JTextField();
        jLabel19 = new javax.swing.JLabel();
        txtValorIva = new javax.swing.JTextField();
        jLabel20 = new javax.swing.JLabel();
        txtDescDoc = new javax.swing.JTextField();
        jLabel21 = new javax.swing.JLabel();
        txtTotalFactura = new javax.swing.JTextField();
        txtFechaDoc = new org.jdesktop.swingx.JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        txtPrecioUnitario = new javax.swing.JTextField();
        btnAgregar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblDetalleDoc = new javax.swing.JTable();
        btnQuitar = new javax.swing.JButton();

        jLabel9.setText("jLabel9");

        javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
        jDialog2.getContentPane().setLayout(jDialog2Layout);
        jDialog2Layout.setHorizontalGroup(
            jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jDialog2Layout.setVerticalGroup(
            jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        cmbFiltroBusqueda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos", "Código Producto", "Descripción", "Aplicación", "Marca Auto", "Año Auto", "Fabricante", "País Origen" }));
        cmbFiltroBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFiltroBusquedaActionPerformed(evt);
            }
        });

        bttBusqueda.setText("Buscar");
        bttBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttBusquedaActionPerformed(evt);
            }
        });

        tblListaBusqueda.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código Producto", "Descripción", "Aplicación", "Marca Auto", "Año Auto", "Fabricante (R)", "Tipo Repuesto"
            }
        ));
        tblListaBusqueda.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblListaBusquedaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblListaBusqueda);

        jLabel3.setText("Resultados");

        jLabel25.setText("- INGRESO DE PRODUCTOS YA EXISTENTES EN STOCK -");

        bttLimpiarB.setText("Limpiar");
        bttLimpiarB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttLimpiarBActionPerformed(evt);
            }
        });

        bttIngresarDocumento.setText("Ingresar");
        bttIngresarDocumento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttIngresarDocumentoActionPerformed(evt);
            }
        });

        jLabel14.setText("Tipo de Documento");

        jLabel15.setText("Nº Documento");

        jLabel16.setText("Filtro de Búsqueda");

        jLabel17.setText("Cantidad:");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED), "Información del Producto Seleccionado", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Consolas", 1, 12), new java.awt.Color(0, 0, 255))); // NOI18N

        jLabel11.setText("Modelo Auto:");

        jLabel12.setText("Fabricantes (R):");

        jLabel8.setText("Marca Auto:");

        jLabel10.setText("Año Auto:");

        lblCodigoProductoB.setText("...");

        lblDescripcionB.setText("...");

        jLabel13.setText("Tipo Repuesto:");

        jLabel6.setText("Aplicación:");

        lblModeloAutoB.setText("...");

        lblFabricanteB.setText("...");

        lblTipoRepuestoB.setText("...");

        jLabel23.setText("Cantidad:");

        jLabel4.setText("Código Producto:");

        lblCantidadB.setText("...");

        jLabel5.setText("Descripción:");

        lblAplicacionB.setText("...");

        lblAñoAutoB.setText("...");

        lblMarcaAutoB.setText("...");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel13)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel23)
                    .addComponent(jLabel8)
                    .addComponent(jLabel10)
                    .addComponent(jLabel11)
                    .addComponent(jLabel12))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblFabricanteB)
                    .addComponent(lblModeloAutoB)
                    .addComponent(lblAñoAutoB)
                    .addComponent(lblMarcaAutoB)
                    .addComponent(lblCantidadB)
                    .addComponent(lblAplicacionB)
                    .addComponent(lblDescripcionB)
                    .addComponent(lblTipoRepuestoB)
                    .addComponent(lblCodigoProductoB))
                .addContainerGap(151, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblCodigoProductoB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(lblDescripcionB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(lblTipoRepuestoB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lblAplicacionB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel23)
                    .addComponent(lblCantidadB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(lblMarcaAutoB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(lblAñoAutoB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(lblModeloAutoB))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(lblFabricanteB))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel2.setText("Fecha");

        lblError.setForeground(new java.awt.Color(255, 51, 51));
        lblError.setText("----");

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jLabel7.setText("Valor Neto");

        jLabel19.setText("IVA");

        jLabel20.setText("Descripción");

        jLabel21.setText("Total Factura");

        txtFechaDoc.setFormats("dd-MM-yyyy");

        jLabel1.setText("Precio Unitario:");

        txtPrecioUnitario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPrecioUnitarioActionPerformed(evt);
            }
        });

        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        tblDetalleDoc.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo de Producto", "Cantidad", "Precio Unitario", "Total"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(tblDetalleDoc);

        btnQuitar.setText("Quitar");
        btnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(304, 304, 304)
                .addComponent(jLabel25)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel20)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel14)
                                        .addComponent(cmbDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel3)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(20, 20, 20)
                                        .addComponent(lblError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(txtDescDoc, javax.swing.GroupLayout.PREFERRED_SIZE, 482, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(jLabel15)
                                                    .addComponent(txtDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addGap(20, 20, 20)
                                                        .addComponent(jLabel2))
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                        .addComponent(txtFechaDoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                .addGap(18, 18, 18)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(txtValorNeto, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                    .addComponent(jLabel7))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(jLabel19)
                                                    .addComponent(txtValorIva, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addGap(0, 0, Short.MAX_VALUE)
                                                        .addComponent(jLabel21)
                                                        .addGap(48, 48, 48))
                                                    .addGroup(layout.createSequentialGroup()
                                                        .addComponent(txtTotalFactura, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGap(0, 0, Short.MAX_VALUE)))))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(bttBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(bttIngresarDocumento)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(118, 118, 118)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel17)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(35, 35, 35)
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txtPrecioUnitario, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnAgregar)
                                        .addGap(18, 18, 18)
                                        .addComponent(btnQuitar))
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(btnCancelar)
                                        .addGap(18, 18, 18)
                                        .addComponent(btnAceptar)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(bttLimpiarB, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addComponent(jLabel16)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cmbFiltroBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(20, 20, 20)
                                .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(263, 263, 263))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addComponent(jLabel25)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel14)
                    .addComponent(jLabel15)
                    .addComponent(jLabel2)
                    .addComponent(jLabel7)
                    .addComponent(jLabel19)
                    .addComponent(jLabel21))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDocumento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtValorNeto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtValorIva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTotalFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtFechaDoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel20)
                    .addComponent(bttIngresarDocumento)
                    .addComponent(txtDescDoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel16)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbFiltroBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bttBusqueda))
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblError))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel17)
                            .addComponent(jLabel1)
                            .addComponent(txtPrecioUnitario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnAgregar)
                            .addComponent(btnQuitar))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnCancelar)
                            .addComponent(btnAceptar)
                            .addComponent(bttLimpiarB)))
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bttLimpiarBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttLimpiarBActionPerformed
        txtBusqueda.setText("");
       
        DefaultTableModel modelBusqueda = (DefaultTableModel) tblListaBusqueda.getModel();
        DefaultTableModel modelDetalleDoc = (DefaultTableModel) tblDetalleDoc.getModel();
        while (modelBusqueda.getRowCount()>0){
            modelBusqueda.removeRow(0);
        }
        while(modelDetalleDoc.getRowCount()>0){
            modelDetalleDoc.removeRow(0);
        }
        lblCodigoProductoB.setText("");
        lblDescripcionB.setText("");
        lblAplicacionB.setText("");
        lblMarcaAutoB.setText("");
        lblAñoAutoB.setText("");
        lblModeloAutoB.setText("");
        lblFabricanteB.setText("");
        lblTipoRepuestoB.setText("");
        lblCantidadB.setText("");
        ComboDto opcion=new ComboDto();
        opcion.setCodigo(-1);
        opcion.setDescripcion("Seleccione");
        cmbDocumento.setSelectedItem(opcion);
        txtBusqueda.setText("");
        txtCantidad.setText("");
        txtDescDoc.setText("");
        txtDocumento.setText("");
        txtPrecioUnitario.setText("");
        txtTotalFactura.setText("");
        txtValorIva.setText("");
        txtValorNeto.setText("");
        
        
        
        
        
    }//GEN-LAST:event_bttLimpiarBActionPerformed

    private void bttIngresarDocumentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttIngresarDocumentoActionPerformed
        boolean sw=false;
        String errores="";
        StockBusiness business=new StockBusiness();
        
        
        if("".equals(txtDocumento.getText())){
            sw=true;
            errores+="Debe ingresar un número de documento\n";
        }
        if(cmbDocumento.getSelectedIndex()==0){
            sw=true;
            errores+="Debe seleccionar un tipo de documento\n";
        }
        if(txtFechaDoc.getDate()==null){
            sw=true;
            errores+="Debe ingresar una fecha\n";
        }
        if("".equals(txtDescDoc.getText())){
            sw=true;
            errores+="Debe ingresar una descripcion del documento\n";
        }       
        if("".equals(txtValorNeto.getText())){
             sw=true;
             errores+="Debe ingresar el valor neto\n";
        }
        if("".equals(txtValorIva.getText())){
            sw=true;
            errores+="Debe ingresar el valor del iva\n";
        }
        if("".equals(txtTotalFactura.getText())){
            sw=true;
            errores+="Debe ingresar el total de la factura";
        }
        if(sw){
                       
           JOptionPane.showMessageDialog(null, errores, "Ingreso de documentos", JOptionPane.PLAIN_MESSAGE);
           
        }
        else{
            
            Integer totalFactura=Integer.valueOf(txtTotalFactura.getText());
            Integer valorNeto=Integer.valueOf(txtValorNeto.getText());
            Integer valorIva=Integer.valueOf(txtValorIva.getText());
            if(totalFactura==valorNeto+valorIva){
                documento=new DocumentoDto();
                documento.setNumeroDocumento(txtDocumento.getText());
                ComboDto opcion=(ComboDto) cmbDocumento.getSelectedItem();
                documento.setTipoDoc(opcion.getCodigo());
                documento.setDescripcion(txtDescDoc.getText());
                documento.setFecha(txtFechaDoc.getDate().getTime());
                documento.setValorNeto(valorNeto);
                documento.setValorIva(valorIva);
                documento.setValorTotal(totalFactura);
            }
            else{
                JOptionPane.showMessageDialog(null, "El valor del total debe ser igual a la suma del valor neto mas el valor iva", "Ingreso de documentos", JOptionPane.PLAIN_MESSAGE);
            }
                
            
        }
            
    }//GEN-LAST:event_bttIngresarDocumentoActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        
    }//GEN-LAST:event_formWindowActivated

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        StockBusiness business=new StockBusiness();
        try {
            
            List lista=business.obtenerTipoDoc();
            Iterator iterador=lista.iterator();
            ComboDto opcion=new ComboDto();
            opcion.setCodigo(-1);
            opcion.setDescripcion("Seleccione");
            cmbDocumento.addItem(opcion);
            while(iterador.hasNext()){
                cmbDocumento.addItem(iterador.next());
            }
        } catch (Exception ex) {
            logger.error("Error:"+ex.getMessage());
            lblError.setText(ex.getMessage());
        }
    }//GEN-LAST:event_formWindowOpened

    private void cmbFiltroBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFiltroBusquedaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbFiltroBusquedaActionPerformed

    private void bttBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bttBusquedaActionPerformed
       DefaultTableModel model = (DefaultTableModel) tblListaBusqueda.getModel();
       while (model.getRowCount()>0){
            model.removeRow(0);
        }
       String texto=txtBusqueda.getText();
       ProductoDto producto=new ProductoDto();
       ProductoBusiness business=new ProductoBusiness();
       switch(cmbFiltroBusqueda.getSelectedIndex()){
           case 0:producto.setFiltroGeneral(texto); break;
           case 1: producto.setCodProducto(texto); break;
           case 2: producto.setDescripcionProducto(texto);break;
           case 3: producto.setAplicacion(texto);break;
           case 4: producto.setMarca(texto);break;
           case 5: producto.setAgnoAuto(texto);break;
           case 6: producto.setFabricante(texto);break;
           case 7: producto.setOrigenRepuesto(texto);break;    
               
       }
        try {
            List lista=business.buscarProductoFiltro(producto);
            Iterator iterador=lista.iterator();
           
            while(iterador.hasNext()){
               producto=(ProductoDto)iterador.next(); 
               Object[] fila=business.obtenerFilaTablaBuscaProd(producto);
               model.addRow(fila);
            }
        } catch (Exception ex) {
            logger.error("Error:"+ex.getMessage());
            lblError.setText(ex.getMessage());
        }
       
    }//GEN-LAST:event_bttBusquedaActionPerformed

    private void tblListaBusquedaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblListaBusquedaMouseClicked
        DefaultTableModel modelTabla = (DefaultTableModel) tblListaBusqueda.getModel();
        ProductoBusiness business=new ProductoBusiness();
        int fila=tblListaBusqueda.getSelectedRow();
        
        ProductoDto producto=new ProductoDto();
        String codigo=(String) tblListaBusqueda.getValueAt(fila, 0);
        String descripcion=(String) tblListaBusqueda.getValueAt(fila, 1);
        String aplicacion = (String) tblListaBusqueda.getValueAt(fila, 2);
        String marca=(String)tblListaBusqueda.getValueAt(fila, 3);
        String agno=(String) tblListaBusqueda.getValueAt(fila, 4);
        String fabricante =(String) tblListaBusqueda.getValueAt(fila, 5);
        String tipoRepuesto=(String) tblListaBusqueda.getValueAt(fila, 6);
        
        lblCodigoProductoB.setText(codigo);
        lblDescripcionB.setText(descripcion);
        lblAplicacionB.setText(aplicacion);
        lblMarcaAutoB.setText(marca);
        lblAñoAutoB.setText(agno);
        lblFabricanteB.setText(fabricante);
        lblTipoRepuestoB.setText(tipoRepuesto);
        try {
            producto.setCodProducto(codigo);
            producto=business.obtenerProducto(producto);
            txtPrecioUnitario.setText(String.valueOf(producto.getValorCompra()));
        } catch (Exception ex) {
            logger.error("Error:"+ex.getMessage());
            lblError.setText(ex.getMessage());
        }
    }//GEN-LAST:event_tblListaBusquedaMouseClicked

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        
        StockBusiness business=new StockBusiness();        
        StockDto stock;
        List lista=new ArrayList();        
        boolean sw=false;
        String errores="";
        if(documento==null){
            sw=true;
            errores+="Debe ingresar los datos del documento\n";
        }
        if(tblDetalleDoc.getRowCount()<=0){
            sw=true;
            errores+="Debe ingresar el detalle del documento";
        }
        if(sw){
            JOptionPane.showMessageDialog(null, errores, "Ingreso de stock", JOptionPane.PLAIN_MESSAGE);
        }
        else{
            
            
            for(int i=0;i<tblDetalleDoc.getRowCount();i++){
                DetalleDocDto detalleDoc=new DetalleDocDto();
                String codProducto=(String) tblDetalleDoc.getValueAt(i, 0);
                Integer cantidad=(Integer) tblDetalleDoc.getValueAt(i, 1);
                Integer valorUnitario=(Integer) tblDetalleDoc.getValueAt(i, 2);
                Integer valorTotal=(Integer) tblDetalleDoc.getValueAt(i, 3);
                detalleDoc.setCantidad(cantidad);
                detalleDoc.setCodigoProducto(codProducto);
                detalleDoc.setValorUnitario(valorUnitario);
                detalleDoc.setValorTotal(valorTotal);
                lista.add(detalleDoc);
            } 
            try {
                business.insertarStocks(lista,documento);
            } catch (Exception ex) {
                logger.error("Error:"+ex.getMessage());
                lblError.setText(ex.getMessage());
            }
        }
            
        
        
            
       
        
        
       
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void txtPrecioUnitarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPrecioUnitarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPrecioUnitarioActionPerformed

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        DefaultTableModel model = (DefaultTableModel) tblDetalleDoc.getModel();
        
        boolean sw=false;
        String errores="";
        if("".equals(txtCantidad.getText())){
            sw=true;
            errores+="Debe ingresar una cantidad\n";
        }
        if("".equals(txtPrecioUnitario.getText())){
            sw=true;
            errores+="Debe ingresar el precio unitario\n";
        }
        if(documento==null){
            sw=true;
            errores+="Debe ingresar los datos del documento\n";
        }
        if("".equals(lblCodigoProductoB.getText())){
            sw=true;
            errores+="Debe seleccionar un producto";
        }
        if(sw){
            JOptionPane.showMessageDialog(null, errores, "Ingreso de stock", JOptionPane.PLAIN_MESSAGE);
        }
        if(!sw){
            
            Integer cantidad=Integer.valueOf(txtCantidad.getText());
            Integer precioUnitario=Integer.valueOf(txtPrecioUnitario.getText());
            String codProducto=lblCodigoProductoB.getText();
            Integer valorTotal=cantidad*precioUnitario;
            for(int i=0;i<model.getRowCount();i++){
                String temp=(String) model.getValueAt(i, 0);
                if(codProducto.equals(temp))
                    sw=true;
            }
            if(sw){
                JOptionPane.showMessageDialog(null, "Ya ingresó stock para este producto. Elimine el existente e ingreselo con la cantidad correcta", "Ingreso de stock", JOptionPane.PLAIN_MESSAGE);
            }
            else{
                Object[] fila={codProducto,cantidad,precioUnitario,valorTotal};            
                model.addRow(fila);
                txtCantidad.setText("");
                txtPrecioUnitario.setText("");
            }
            
        }
        
        
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarActionPerformed
        DefaultTableModel model = (DefaultTableModel) tblDetalleDoc.getModel();
        int fila=tblDetalleDoc.getSelectedRow();
        if(fila!=-1){
            model.removeRow(fila);
        }
        else
            JOptionPane.showMessageDialog(null, "Debe seleccionar un registro", "Ingreso de stock", JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_btnQuitarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
       this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IngresoPPExistenteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IngresoPPExistenteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IngresoPPExistenteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IngresoPPExistenteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new IngresoPPExistenteGui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnQuitar;
    private javax.swing.JButton bttBusqueda;
    private javax.swing.JButton bttIngresarDocumento;
    private javax.swing.JButton bttLimpiarB;
    private javax.swing.JComboBox cmbDocumento;
    private javax.swing.JComboBox cmbFiltroBusqueda;
    private javax.swing.JDialog jDialog2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblAplicacionB;
    private javax.swing.JLabel lblAñoAutoB;
    private javax.swing.JLabel lblCantidadB;
    private javax.swing.JLabel lblCodigoProductoB;
    private javax.swing.JLabel lblDescripcionB;
    private javax.swing.JLabel lblError;
    private javax.swing.JLabel lblFabricanteB;
    private javax.swing.JLabel lblMarcaAutoB;
    private javax.swing.JLabel lblModeloAutoB;
    private javax.swing.JLabel lblTipoRepuestoB;
    private javax.swing.JTable tblDetalleDoc;
    private javax.swing.JTable tblListaBusqueda;
    private javax.swing.JTextField txtBusqueda;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtDescDoc;
    private javax.swing.JTextField txtDocumento;
    private org.jdesktop.swingx.JXDatePicker txtFechaDoc;
    private javax.swing.JTextField txtPrecioUnitario;
    private javax.swing.JTextField txtTotalFactura;
    private javax.swing.JTextField txtValorIva;
    private javax.swing.JTextField txtValorNeto;
    // End of variables declaration//GEN-END:variables
}
